/**
 * mem_stream.c
 *
 *  Created on: 2019-09-05
 *      Author: chenshisheng
 */

#include "stream/mem_stream.h"

static int _Put(void *instance, unsigned char b)
{
    MemStream_t *ms = instance;

    if(ms->eos >= ms->size)
    {
        return 0;
    }

    ms->buffer[ms->eos] = b;
    ms->eos ++;
    return 1;
}

static int _Get(void *instance, unsigned char *pb)
{
    MemStream_t *ms = instance;

    if(ms->offset >= ms->eos)
    {
        return 0;
    }

    *pb = ms->buffer[ms->offset];
    ms->offset ++;
    return 1;
}

static void _Flush(void *instance)
{
    MemStream_t *ms = instance;

    ms->eos = 0;
    ms->offset = 0;
}

void MemStream_Init(MemStream_t *ms, void *buf, unsigned int size)
{
    Stream_InitWithoutMutex(&ms->stream, _Put, _Get, _Flush);
    ms->buffer = buf;
    ms->size = size;
    ms->eos = 0;
    ms->offset = 0;
}

void MemStream_Reset(MemStream_t *ms)
{
    ms->eos = 0;
    ms->offset = 0;
}

unsigned int MemStream_DataSize(MemStream_t *ms)
{
    return ms->eos - ms->offset;
}

unsigned int MemStream_Space(MemStream_t *ms)
{
    return ms->size - ms->eos;
}

void *MemStream_Data(MemStream_t *ms)
{
    return ms->buffer + ms->offset;
}
